package com.codemate.interview.rabbit;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * rabbit配置
 *
 * @author hice
 */
@Slf4j
@Configuration
public class RabbitConfig {

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory factory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(factory);
        // 设置监听确认mq（交换器）接受到信息
        rabbitTemplate.setConfirmCallback(confirmCallback());
        // 添加监听 失败鉴定（路由没有收到）
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setReturnCallback(returnCallback());
        return rabbitTemplate;
    }


    /**
     * 生产者发送确认
     *
     * @return .
     */
    @Bean
    public RabbitTemplate.ConfirmCallback confirmCallback() {
        return (correlationData, ack, cause) -> {
            if (ack) {
                log.debug("发送者确认发送给mq成功，cause：{}", cause);
            } else {
                log.debug("发送者发送失败，考虑重发，cause：{}", cause);
            }
        };
    }

    /**
     * 失败通知
     *
     * @return .
     */
    @Bean
    public RabbitTemplate.ReturnCallback returnCallback() {
        return (message, replyCode, replyText, exchange, routingKey) -> {
            // 无效路由信息，需要考虑另外处理
            log.debug("Returned replyCode: {}", replyCode);
            log.debug("Returned replayText: {}", replyText);
            log.debug("Returned exchange: {}", exchange);
            log.debug("Returned routingKey: {}", routingKey);
            log.debug("Returned Message: {}", new String(message.getBody()));
        };
    }

}
